﻿using EmitMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zqdn.Services.Interfaces.ProvinceCity;
using zqdn.Web.Helpers;
using zqdn.Web.ViewModels;
using zqdn.Web.Extensions;
using zqdn.Web.App_Start;
using zqdn.Web.Filters;
using zqdn.Services.Auth;
using zqdn.Models.Auth;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;
using zqdn.Services.Interfaces.Case;
using zqdn.Models.Ex;
using zqdn.Models.Case;
using zqdn.Web;
using zqdn.Services.Interfaces.Ex;

namespace zqdn.Web.Areas.Admin.Controllers
{

    public class CaseController : Controller
    {
        private readonly ICaseService _caseService;
        private readonly IUserService _userService;
        private readonly IExService _iexrepository;
        private readonly IGoodService _igoodrepository;

        public CaseController(ICaseService _caseService, IUserService _userService, IExService _iexrepository, IGoodService _igoodrepository)
        {
            this._caseService = _caseService;
            this._userService = _userService;
            this._iexrepository = _iexrepository;
            this._igoodrepository = _igoodrepository;
        }

        // GET: Admin/User
        [NormalAuthFilter(_role = (int)zqdn.Web.Helpers.Role.超级管理员)]
        public ActionResult Index(int? page = 1, int? caseId=0)
        {
            var casetpls = _caseService.GetCaseList(page: (int)page, size: GlobalConfig.DefaultPageSize);
            var changelogsViewModels = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<List<CaseTpl>, List<ViewModels.CaseTplViewModel>>().Map(casetpls.ToList());
            if (caseId != 0)
            {
                changelogsViewModels = changelogsViewModels.Where(o => o.ID == caseId).ToList();
            }
            var pagedList = new PagedList.StaticPagedList<ViewModels.CaseTplViewModel>(changelogsViewModels, casetpls.GetMetaData());

            return View(pagedList);
        }

        public ActionResult pass(int id)
        {
            string result = "0";
           
            try 
	        {	        
		           CaseTpl ctp = _caseService.getCaseByID(id);
                   var re = _userService.GetUserByID(ctp.CreateUserID);
                    if(ctp != null){
                        ctp.Status = 1;
                        _caseService.UpdateCase(ctp);
                        //TODO  添加积分
                        //new ExController().
                        ExViewModel model = new ExViewModel();
                        model.EID = id;
                        model.Type = 3;
                        model.UID = ctp.CreateUserID;
                        model.openID = re.OpenId;
                        new zqdn.Web.Controllers.ExController(_userService,_iexrepository,_igoodrepository).AddExLog(model);
                        result = "1";
                    }
	        }
	        catch (Exception ex)
	        {
                return Content(result);
	        }

            return Content(result);
        }
        public ActionResult notpass(int id)
        {
            string result = "0";

            try
            {
                CaseTpl ctp = _caseService.getCaseByID(id);
                var re = _userService.GetUserByID(ctp.CreateUserID);
                if (ctp != null)
                {
                    ctp.Status = 0;
                    _caseService.UpdateCase(ctp);
                    //取消减去积分
                    ExViewModel model = new ExViewModel();
                    model.EID = id;
                    model.Type = 5;
                    model.UID = ctp.CreateUserID;
                    model.openID = re.OpenId;
                    new zqdn.Web.Controllers.ExController(_userService, _iexrepository, _igoodrepository).AddExLog(model);
                    result = "1";
                }
            }
            catch (Exception ex)
            {
                return Content(result);
            }

            return Content(result);
        }

        public ActionResult CaseInfo(int id)
        {
            CaseTpl tpl = _caseService.getCaseByID(id);
            return View(tpl);
        }

        public void ExportExcel()
        {
            String str = WebConfigurationManager.ConnectionStrings["DB_Zqdn"].ToString();
            SqlConnection conn = new SqlConnection();
            string sql = @"select b.ID 病例编号,a.UserName 手机,a.Name 创建人姓名,b.CreatedTime 上传日期,(case when b.Status=1 then '审核通过' else '未通过审核' end) 审核状态,
b.WriteTime 日期,(case  when b.Type = 0 then '凯特力吸入麻醉病例收集' else '艾诺联合病例收集' end) 病例类型,
b.ZyNo 住院号,b.CNo 床号,b.Name 姓名,b.Sex 性别,b.Age 年龄,b.Weight 体重,
b.Med_YDQ,b.Med_WCQ,b.Med_SXQ,b.MedCom_YDQ,b.MedCom_WCQ,b.MedCom_SXQ,
b.MedCf_BTFN,b.MedCf_YMTMD,b.Med_PW_1,b.Med_PW_2,b.Med_PW_3,b.Med_PW_4,
b.CaseImg 图片路径,b.ActiveHos 完成医院,b.ActiveID 完成人,b.Med_GZ 转归情况
  from Users as a
join CaseTpls as b
on a.ID = b.CreateUserID";
            conn.ConnectionString = str;
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            CreateExcel(table, "application/ms-excel", "病例明细");
        }

        public void CreateExcel(DataTable dt, string FileType, string FileName)
        {
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.Buffer = true;
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
            Response.ContentType = FileType;
            string colHeaders = string.Empty;
            string ls_item = string.Empty;
            DataRow[] myRow = dt.Select();
            int i = 0;
            int cl = dt.Columns.Count;

            var tempList = new List<int[]>();

            for (int key = 0; key < cl; key++)
            {
                var temp = dt.Columns[key].ToString();;
                switch (temp)
                {
                    //用药方案
                    case "Med_YDQ":
                    {
                        Response.Output.Write("用药方案-诱导期-挥发罐刻度" + "\t");
                        Response.Output.Write("用药方案-诱导期-氧气流量" + "\t");
                        Response.Output.Write("用药方案-诱导期-应用时间" + "\t");
                        tempList.Add(new int[2] { key, 3});

                    };break;
                    case "Med_WCQ":
                        {
                            Response.Output.Write("用药方案-维持期-挥发罐刻度" + "\t");
                            Response.Output.Write("用药方案-维持期-氧气流量" + "\t");
                            Response.Output.Write("用药方案-维持期-应用时间" + "\t");
                            tempList.Add(new int[2] { key, 3 });

                        }; break;
                    case "Med_SXQ":
                        {
                            Response.Output.Write("用药方案-苏醒期-挥发罐刻度" + "\t");
                            Response.Output.Write("用药方案-苏醒期-氧气流量" + "\t");
                            Response.Output.Write("用药方案-苏醒期-应用时间" + "\t");
                            tempList.Add(new int[2] { key, 3 });

                        }; break;
                    //合并用药
                    case "MedCom_YDQ":
                        {
                            Response.Output.Write("合并用药-诱导期-药品名称" + "\t");
                            Response.Output.Write("合并用药-诱导期-商品名" + "\t");
                            Response.Output.Write("合并用药-诱导期-规格" + "\t");
                            Response.Output.Write("合并用药-诱导期-数量" + "\t");
                            tempList.Add(new int[2] { key,4 });

                        }; break;
                    case "MedCom_WCQ":
                        {
                            Response.Output.Write("合并用药-维持期-药品名称" + "\t");
                            Response.Output.Write("合并用药-维持期-商品名" + "\t");
                            Response.Output.Write("合并用药-维持期-规格" + "\t");
                            Response.Output.Write("合并用药-维持期-数量" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    case "MedCom_SXQ":
                        {
                            Response.Output.Write("合并用药-苏醒期-药品名称" + "\t");
                            Response.Output.Write("合并用药-苏醒期-商品名" + "\t");
                            Response.Output.Write("合并用药-苏醒期-规格" + "\t");
                            Response.Output.Write("合并用药-苏醒期-数量" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    //药物配方
                    case "MedCf_BTFN":
                        {
                            Response.Output.Write("药物配方-布托啡诺-PCA背景输注" + "\t");
                            Response.Output.Write("药物配方-布托啡诺-单次剂量" + "\t");
                            Response.Output.Write("药物配方-布托啡诺-锁定时间" + "\t");
                            Response.Output.Write("药物配方-布托啡诺-术后镇痛总时长" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    case "MedCf_YMTMD":
                        {
                            Response.Output.Write("药物配方-右美托咪啶-PCA背景输注" + "\t");
                            Response.Output.Write("药物配方-右美托咪啶-单次剂量" + "\t");
                            Response.Output.Write("药物配方-右美托咪啶-锁定时间" + "\t");
                            Response.Output.Write("药物配方-右美托咪啶-术后镇痛总时长" + "\t");
                            tempList.Add(new int[2] { key, 4 });
                        }; break;
                    //其他配伍药物
                    case "Med_PW_1":
                        {
                            Response.Output.Write("其他配伍药物-药品名称" + "\t");
                            Response.Output.Write("其他配伍药物-药品名称" + "\t");
                            Response.Output.Write("其他配伍药物-药品名称" + "\t");
                            Response.Output.Write("其他配伍药物-药品名称" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    case "Med_PW_2":
                        {
                            Response.Output.Write("其他配伍药物-商品名" + "\t");
                            Response.Output.Write("其他配伍药物-商品名" + "\t");
                            Response.Output.Write("其他配伍药物-商品名" + "\t");
                            Response.Output.Write("其他配伍药物-商品名" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    case "Med_PW_3":
                        {
                            Response.Output.Write("其他配伍药物-规格" + "\t");
                            Response.Output.Write("其他配伍药物-规格" + "\t");
                            Response.Output.Write("其他配伍药物-规格" + "\t");
                            Response.Output.Write("其他配伍药物-规格" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    case "Med_PW_4":
                        {
                            Response.Output.Write("其他配伍药物-数量" + "\t");
                            Response.Output.Write("其他配伍药物-数量" + "\t");
                            Response.Output.Write("其他配伍药物-数量" + "\t");
                            Response.Output.Write("其他配伍药物-数量" + "\t");
                            tempList.Add(new int[2] { key, 4 });

                        }; break;
                    default:{
                        Response.Output.Write(temp + "\t");
                    }
                    break;
                }
                
            }
            Response.Output.Write("\n");

            foreach (DataRow row in myRow)
            {
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))
                    {
                        ls_item += row[i].ToString().Replace("\t", "").Replace("\n", "") + "\n";
                    }
                    else
                    {
                        bool hit = false;
                        var tempR = row[i].ToString().Replace("\t", "").Replace("\n", "");
                        foreach (var item in tempList)
                        {
                            //命中要处理的字段
                            if (item[0] == i)
                            {
                                hit = true;
                                //没有填
                                if (string.IsNullOrEmpty(tempR))
                                {
                                    for (int innerI = 0; innerI < item[1]; innerI++)
                                    {
                                        ls_item += "\t";
                                    }
                                }
                                else
                                {
                                    //有值，则过滤&amp;，然后切割
                                    string [] str = tempR.Replace("&amp;","&").Split('&');
                                    foreach (var item1 in str)//数据无异常，即切出来正好
                                    {
                                        ls_item += item1 + "\t";
                                    }
                                    if(str.Length != item[1]){
                                        //否则，切到几位赋几位，剩下的填空
                                        for (int i2 = 0; i2 < (item[1] - str.Length); i2++)
                                        {
                                            ls_item += "\t";
                                        }
                                    }
                                     
                                }
                            }
                        }
                        if (!hit) { 
                        ls_item += tempR + "\t";
                        }
                    }
                }
                Response.Output.Write(ls_item);
                ls_item = string.Empty;
            }
            Response.Output.Flush();
            Response.End();
        }


    }
}